<?php
namespace App\Traits;


/**
 * 无限级分类
 * Class SortBehavior
 * @package app\behaviors
 * @property integer $id
 * @property string $sort
 */
trait Sortable
{
    public function getSortNameLabel()
    {
        return 'name';
    }
    public function getSortName()
    {
        $getSortNameLabel = $this->getSortNameLabel();
        return $this->getNbsp(8).$this->$getSortNameLabel;
    }

    public function getNbsp($time,$otherCount = null)
    {
        $count = $otherCount ? $otherCount : $this->getSortCount();
        $str = ' ';
        return str_repeat($str,$count*$time);
    }

    public function getSortCount()
    {
        return count(explode(',',$this->sort))-1;
    }
    /**
     * 返回树
     * @param $id
     * @param string $attribute
     * @return array
     */
    public function getTree($id,$attribute = 'id')
    {
        $models = $this->getTreeModels($id);
        $data = [];
        foreach ($models as $model)
        {
            $data[] = $model->$attribute;
        }
        return $data;
    }

    /**
     * 获取子孙节点
     */
    public function getChildrenAndThis($attribute='id'){
        /** @var  $class \Eloquent*/
        $data = [];
        $class = get_class($this);
        $thisModel = $this;
        $sort = $thisModel->sort.','.$thisModel->id;
        $models = $class::where('sort','like',$sort.'%')->all();
        $models[] = $thisModel;
        foreach($models as $model)
        {
            $data[$model->$attribute] = $model->$attribute;
        }
        return $data;
    }

    protected function getTreeModels($id)
    {
        /** @var  $class \Eloquent*/
        $class = get_class($this);
        $thisModel = $class::find($id);
        $models = $class::where("id in (".$thisModel->sort.")")->all();
        $models[] = $thisModel;
        return $models;
    }
}